<template>
  <el-drawer
    v-model="drawer"
    :title="formModel.id ? '编辑文章' : '添加文章'"
    label-width="120px"
    :close-on-click-modal="false"
    :direction="direction"
    size="50%">
    <el-form ref="formRef" :model="formModel" class="demo-ruleForm">
      <el-form-item label="文章标题">
        <el-input v-model="formModel.title" />
      </el-form-item>
      <el-form-item label="文章分类">
        <el-select
          v-model="formModel.cate_id"
          placeholder="请选择"
          style="width: 100%">
          <!-- label是展示的，value是值是提交的 -->
          <el-option
            v-for="item in cateListData"
            :key="item.cate_id"
            :label="item.cate_name"
            :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="文章封面">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :on-change="handleAvatarSuccess"
          :auto-upload="false"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon
            v-else
            class="avatar-uploader-icon"
            :size="40"
            color="#dcdfe6">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容">
        <div class="editor">
          <quill-editor
            ref="myQuillEditor"
            v-model:content="formModel.content"
            :options="data.editorOption"
            content-type="html" />
        </div>
      </el-form-item>
      <el-form-item style="padding-left: 70px">
        <el-button size="large" class="publish" @click="publish('已发布')"
          >发布</el-button
        >
        <el-button size="large" @click="publish('草稿')">暂存</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<script setup>
import { ref, reactive } from 'vue';
// 局部引入
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
const data = reactive({
  content: '',
  editorOption: {
    modules: {
      toolbar: [
        ['bold', 'italic', 'underline', 'strike'],
        [{ size: ['small', false, 'large', 'huge'] }],
        [{ font: [] }],
        [{ align: [] }],
        [{ list: 'ordered' }, { list: 'bullet' }],
        [{ indent: '-1' }, { indent: '+1' }],
        [{ header: 1 }, { header: 2 }],
        ['image'],
        [{ direction: 'rtl' }],
        [{ color: [] }, { background: [] }]
      ]
    },
    placeholder: '请输入内容...'
  }
});
const drawer = ref(false);
const direction = ref('rtl');
const formModel = ref({
  title: '',
  cate_id: '',
  cover_img: '',
  content: '',
  state: ''
});
// 文章分类下拉框
import {
  cateListApi,
  articlePublishApi,
  articleInfoApi,
  editArticleApi
} from '@/api/article';
const emits = defineEmits(['updata']);
const publish = async (state) => {
  console.log(state, '发布状态');
  formModel.value.state = state;
  const fm = new FormData();
  for (let key in formModel.value) {
    fm.append(key, formModel.value[key]);
  }
  console.log(fm, 'formModel');
  if (formModel.value.id) {
    // 编辑  提交
    await editArticleApi(fm);
    ElMessage.success('修改成功');
    drawer.value = false;
  } else {
    // 添加 提交
    const res = await articlePublishApi(fm);
    ElMessage.success(res.message);
    drawer.value = false;
  }
  emits('updata');
};
let cateListData = ref([]);
const getCateList = async () => {
  const res = await cateListApi();
  cateListData.value = res.data;
  console.log(cateListData.value, '文章分类下拉框');
};
const myQuillEditor = ref();
const open = async (row) => {
  getCateList();
  drawer.value = true;
  if (row.id) {
    // 发请求回显数据
    const res = await articleInfoApi(row.id);
    console.log(res, '回显的数据');
    formModel.value = res.data;
    // 图片回显
    imageUrl.value =
      'http://big-event-vue-api-t.itheima.net' + formModel.value.cover_img;
    // 回显富文本内容
    myQuillEditor.value.setHTML(res.data.content);
    const file = await imageUrlToFileObject(imageUrl.value, 'image');
    console.log(file, '回显图片');
    formModel.value.cover_img = file;
  } else {
    console.log('添加');
    myQuillEditor.value.setHTML('');
    imageUrl.value = '';
    formModel.value = {
      title: '',
      cate_id: '',
      cover_img: '',
      content: '',
      state: ''
    };
  }
};
import axios from 'axios';
// 将网络图片地址转换为 File 对象的函数
async function imageUrlToFileObject(imageUrl, filename) {
  try {
    // 使用 Axios 下载图片数据
    const response = await axios.get(imageUrl, { responseType: 'arraybuffer' });

    // 将下载的数据转换成 Blob 对象
    const blob = new Blob([response.data], {
      type: response.headers['content-type']
    });

    // 创建 File 对象
    const file = new File([blob], filename, {
      type: response.headers['content-type']
    });

    return file;
  } catch (error) {
    console.error('Error converting image URL to File object:', error);
    return null;
  }
}
defineExpose({
  drawer,
  open
});
import { Plus } from '@element-plus/icons-vue';

const imageUrl = ref('');
const handleAvatarSuccess = (file) => {
  console.log(file, '上传成功');
  imageUrl.value = URL.createObjectURL(file.raw); //预览图片
  formModel.value.cover_img = file.raw;
};
const beforeAvatarUpload = (rawFile) => {
  console.log(rawFile.size / 1024 / 1024, '上传前');
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片格式要求为 jpeg/png/jpg');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 20) {
    ElMessage.error('图片不能超过20MB!');
    return false;
  }
  return true;
};
</script>
<style>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style lang="less" scoped>
:deep(.ql-editor) {
  min-height: 300px;
}

.publish {
  background-color: #415845;
  color: #fff;
}

:deep(.ql-formats) {
  height: 21px;
  line-height: 21px;
}

:deep(.ql-container.ql-snow) {
  width: 100% !important;
}

:deep(.el-form-item__label) {
  font-weight: 600 !important;
}

:deep(.avatar-uploader .el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  margin-bottom: 20px;
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

:deep(.el-drawer__header) {
  padding-bottom: 20px;
  border-bottom: 1px solid #415845;
  margin-bottom: 0;
}
</style>
